package com.banyuan.servlet.image;


import com.alibaba.fastjson.JSON;
import com.banyuan.domain.ResData;
import com.banyuan.utils.CommonUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet("/img/upload")
public class ImageUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        FileItemFactory fileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);

        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(req);
            FileItem fileItem = fileItems.get(0);
            String name = fileItem.getName(); // 上传的文件名

            String randomStr = CommonUtils.getRandomStr(); // 获得随机字符串
            String fileName = randomStr + name; // 生成随机文件名

            fileItem.write(new File("/Users/edy/Desktop/fuxi/"+fileName));
            resp.getWriter().write(JSON.toJSONString(new ResData(200,"ok",fileName)));




        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
